<?php 

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Member extends CI_Controller {
    function Member() {
        parent::__construct();
        $this->load->helper('html');
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->helper('file');
        $this->load->helper('captcha');
        
        if (!isset($_SESSION)) {
            session_start();
        }
    }

    public function detail()
    {
        $data['message'] = "";
        $member_id = $this->uri->segment(3);
        
        if($member_id)
        {
            //Query: Car list
            $this->load->model('Member_model');
            $data['dealer_list'] = $this->Member_model->get_member_by_id($member_id);
            
            $this->load->model('Car_model');
            $car_list = $this->Car_model->get_approved_car_by_member_id($member_id);
            $car_list = array_slice($car_list->result(), 0, $car_list->num_rows);
            $data['car_list'] = $car_list;

            $this->load->model('Service_model');
            $data['service_list'] = $this->Service_model->get_approved_service_by_member_id($member_id);

            $this->load->model('Part_model');
            $data['part_list'] = $this->Part_model->get_approved_part_by_member_id($member_id);

            $this->load->view('header', $data);
            $this->load->view('templates/member/member_detail', $data);

            $data['make']= $this->db->get('psacar_make');
            $this->load->view('footer', $data); 
        }
        else
            redirect(base_url().'index.php/service/search');
    }
    
    public function result() {
        $data['message'] = "";
        
        $make = $this->input->post('make');
        $model = $this->input->post('model');
        $year = $this->input->post('year');

        $this->load->model('Member_model');
        $data['member_list'] = $this->Member_model->get_member_list(
            $make, 
            $model, 
            $year);

        $this->load->view('header',$data);
        $this->load->view('member_list_view',$data);
        $data['make']= $this->db->get('psacar_make');
        $this->load->view('footer',$data);        
    }
    
    public function login()
    {
        $email = $this->security->xss_clean($this->input->post('email'));
        $password = $this->security->xss_clean($this->input->post('password'));

        $this->load->model('Member_model');
        $result = $this->Member_model->login($email, $password);
                 
        if(!$result)
        {
            $msg = '<font color=red>Invalid username and/or password.</font>&nbsp;<a href="../resetpassword">Forget password?</a><br/>';
            $data['message'] = $msg;
            
            $data['service']= $this->db->get('psacar_service');
            $data['location']= $this->db->get('psacar_location');

            $this->load->view('header', $data);
            $this->load->view('sell', $data);
            $data['make']= $this->db->get('psacar_make');
            $this->load->view('footer', $data);            
        }
        else {
            if(!$this->session->userdata('activated')) {
                $data = array(
                    'validated' => false);
                $this->session->set_userdata($data);
                $this->session->sess_destroy();
                $msg = '<font color=red>Your account is not yet activated. Please check your mail for activation link.</font>';
                $data['message'] = $msg;

                $data['service']= $this->db->get('psacar_service');
                $data['location']= $this->db->get('psacar_location');

                $this->load->view('header', $data);
                $this->load->view('sell', $data);
                $data['make']= $this->db->get('psacar_make');
                $this->load->view('footer', $data);                
            }
            else {
                if ($this->session->userdata('membership') != 4)
                    redirect(base_url() . 'index.php/sell/result');
                else 
                    redirect(base_url());                
            }
        }
    }
    
    public function logout()
    {
        $this->session->sess_destroy();
        redirect(base_url());
    }
    
    public function register()
    {                  
        if($this->session->userdata('validated'))
            redirect(base_url().'index.php');
        else
        {
            $this->load->model('Member_model');
            $username = $this->input->post('username');
            $email = $this->input->post('email');
            $email = str_replace(' ', '', $email);
            $phone = $this->input->post('phone_number');
            $phone = str_replace(' ', '', $phone);

            $member_type = $this->input->post('member_type');            
            switch ($member_type)
            {
                case 3:
                    $email = $this->input->post('company_email');
                    $phone = $this->input->post('contact_phone_1');
                    break;
            }
                        
            //Existing email?
            $member = $this->Member_model->get_member_by_email($email);
            $existing_mail = $member->num_rows != 0;
            
            //Existing username?
            $existing_user = false;
            if(!$existing_mail) {
                $member = $this->Member_model->get_member_by_login($username);
                $existing_user = $member->num_rows != 0;
            }
            
            if ((!$existing_mail) && (!$existing_user)) {                
                $page_view = 'information';

                $this->load->database();                            
                $member = array(
                    'type_id' => $member_type,
                    'name' => $username,
                    'password' => $this->input->post('password'),
                    'contact_phone_1' => $phone,
                    'email' => $email,
                    
                    'first_name' => $this->input->post('firstname'),
                    'last_name' => $this->input->post('lastname'),
                    'gender' => $this->input->post('gender'),
                    'number_vehicle' => $this->input->post('number_vehicle'),

                    'company' => $this->input->post('company_name'),
                    'website' => $this->input->post('website'),
                    'address' => $this->input->post('company_name'),
                    'contact_phone_2' => $this->input->post('contact_phone_2'),
                    
                    'created_date'=>date("Y-m-d"),
                    'modified_date'=>date("Y-m-d"));

                if ($this->input->post('occupation'))
                    $member['occupation_id'] = $this->input->post('occupation');

                if ($this->input->post('industry'))
                    $member['industry_id'] = $this->input->post('industry');

                $all_car_type = '';
                if ($this->input->post('car_type')) {                        
                    if(is_array($this->input->post('car_type'))){
                        foreach ($this->input->post('car_type') as $a_car_type)
                            $all_car_type = $all_car_type . $a_car_type . ',';
                    }

                    if(substr($all_car_type, strlen(',') * -1) == ',') {
                        $all_car_type = substr($all_car_type, 0, strlen($all_car_type) - 1);
                        $member['car_type'] = $all_car_type;
                    }                        
                }                

                $this->db->insert('psacar_member', $this->security->xss_clean($member));
                $member_id = $this->db->insert_id();
                
                //Reference number
                $member_code = '';
                $type_code_list = $this->db->get_where(
                    'psacar_member_type', 
                    array('id' => $member_type));
                if ($type_code_list->num_rows != 0) {
                    $type_code = $type_code_list->row();
                    $member_code = $type_code->short_code;
                }
                
                $member_code .= 
                    substr('00000' . $member_id, -5) . 
                    random_string('alnum', 3);
                $data['code'] = $member_code;
                $this->db->where('id', $member_id);
                $this->db->update('psacar_member', $data);
                
                $expiration_date = new DateTime(date('Y-m-d'));
                $expiration_date->add(new DateInterval('P30D'));            
                
                //Service
                unset($data['code']);
                $service_product = '';
                if ($this->input->post('service')) {
                    if(is_array($this->input->post('service'))){
                        foreach ($this->input->post('service') as $a_service) {
                            $member_service =  array(
                                'member_id' => $member_id,
                                'service_id' => $a_service,
                                //'location_id' => $location,
                                //'make_id' => $a_make,
                                'status' => 0,
                                'expiration_date' => $expiration_date->format("Y-m-d"));

                            $this->db->insert('psacar_member_service', $this->security->xss_clean($member_service));
                            $member_service_id = $this->db->insert_id();

                            //Reference number
                            $ref_code = '';
                            $service_code_list = $this->db->get_where('psacar_service', array('id' => $a_service));
                            if ($service_code_list->num_rows != 0) {
                                $service_code = $service_code_list->row();
                                $ref_code = $service_code->code;
                            }

                            $ref_code .= 
                                substr('00000' . $member_service_id, -5) . 
                                random_string('alnum', 3);
                            $data['ref_code'] = strtoupper($ref_code);

                            $this->db->where('id', $member_service_id);
                            $this->db->update('psacar_member_service', $data);                             
                        }                            
                    }
                }

                //Product
                if ($this->input->post('product')) {
                    if(is_array($this->input->post('product'))){
                        foreach ($this->input->post('product') as $a_product) {
                            $member_part =  array(
                                'member_id' => $member_id,
                                'part_id' => $a_product,
                                //'location_id' => $location,
                                //'make_id' => $a_make,
                                'status' => 0,
                                'expiration_date' => $expiration_date->format("Y-m-d"));
                            
                            $this->db->insert('psacar_member_part', $this->security->xss_clean($member_part));
                            $member_part_id = $this->db->insert_id();

                            //Reference number
                            $ref_code = '';
                            $part_code_list = $this->db->get_where('psacar_part', array('id' => $a_product));
                            if ($part_code_list->num_rows != 0) {
                                $part_code = $part_code_list->row();
                                $ref_code = $part_code->code;
                            }

                            $ref_code .= 
                                substr('00000' . $member_part_id, -5) . 
                                random_string('alnum', 3);
                            $data['ref_code'] = strtoupper($ref_code);

                            $this->db->where('id', $member_part_id);
                            $this->db->update('psacar_member_part', $data);  
                        }
                    }
                }

                $mail_message = $this->message_register(
                    $member_id,
                    $username,
                    $email);

                $this->sendmail(
                    $email, 
                    'Welcome to psacar.com  - Your Registration is Pending Approval', 
                    $mail_message);
                
                $data['member_type'] = '';
                $data['message_title'] = "Thank you for your registration. ";
                $data['message_body'] = "Confirmation has been sent to your email address. Check your email to complete your registration.";

                $this->load->view('header', $data);
                $data['service']= $this->db->get('psacar_service');
                $data['location']= $this->db->get('psacar_location');            
                $this->load->view($page_view, $data);
                $data['make']= $this->db->get('psacar_make');
                $this->load->view('footer', $data);
            }
            else {
                if($existing_mail)
                    $message = "Registration failed due to existing email";
                
                if($existing_user)
                    $message = "Registration failed due to existing username";
                //$this->signup($message);
                $this->signup_form('', $message);
            }            
        }
    }
        
    public function signup()
    {                
        if($this->session->userdata('validated'))
            redirect(base_url().'index.php');
        else
        {
            $target_type = $this->uri->segment(3);
            if(!$target_type)
                $target_type = ' ';
            
            $this->signup_form($target_type, '');
        }
    }
    
    private function signup_form($target_type, $message)
    {        
        $data['message'] = $message;
        
        $data['target_type'] = $this->db->get_where(
            'psacar_member_type', 
            array('code' => $target_type));

        $data['car_type'] = $this->db->get('psacar_car_type');
        $data['member_type'] = $this->db->get('psacar_member_type');

        $this->db->where('parent_id', '0');
        $this->db->order_by('id', 'asc');
        $data['service'] = $this->db->get('psacar_service');

        $this->db->where('parent_id', '0');
        $this->db->order_by('id', 'asc');
        $data['product'] = $this->db->get('psacar_part');

        $data['location'] = $this->db->get('psacar_location');            
        $data['occupation'] = $this->db->get('psacar_occupation');

        $this->db->order_by("order", "asc");
        $this->db->order_by("industry", "asc"); 
        $data['industry'] = $this->db->get('psacar_industry');

        $data['captcha'] = $this->captcha(false);
        
        $this->load->view('header', $data);
        $this->load->view('templates/member/member_signup', $data);
        $data['make']= $this->db->get('psacar_make');                
        $this->load->view('footer', $data);        
    }
    
    private function encrypt_member_id($member_id)
    {
        $crypto_key = 'member';
        $encrypted = base64_encode(
            mcrypt_encrypt(
                MCRYPT_RIJNDAEL_256, 
                md5($crypto_key), 
                $member_id, 
                MCRYPT_MODE_CBC, 
                md5(md5($crypto_key))));

        if(substr($encrypted, strlen('=') * -1) == '=')
            $encrypted = substr($encrypted, 0, strlen($encrypted) - 1);

        return $encrypted;
    }
    
    private function decrypt_member_id($member_token)
    {
        $crypto_key = 'member';
        $decrypted = rtrim(
            mcrypt_decrypt(
                MCRYPT_RIJNDAEL_256, 
                md5($crypto_key), 
                base64_decode($member_token), 
                MCRYPT_MODE_CBC, md5(md5($crypto_key))), 
            "\0");

        return $decrypted;
    }    
  
    public function message_register($member_id, $member_name, $member_email)
    {
        //Encrypt member id
        $encrypted_id = $this->encrypt_member_id($member_id);
        
        $mail_message = 
            '<div style="padding:0px;margin:0px;font-family:"' . 
            "'Helvetica Neue'" . 
            ',Helvetica,Arial;font-size:12px;color:#5e5959">';
        $mail_message .= '<table cellspacing="0" cellpadding="0" border="0" bgcolor="#f6f6f6" align="center">';
        $mail_message .= '<tbody>';
        $mail_message .= '<tr>';
        $mail_message .= '<td width="750">';
        $mail_message .= '<table width="100%" align="center">';
        $mail_message .= '<tbody>';
        $mail_message .= '<tr>';
        $mail_message .= '<td width="100%" bgcolor="#003466" style="color:#fff;padding:3px;text-align:center;font-size:10px">';
        $mail_message .= 'Contact us by phone at <a target="_blank" href="tel:096%208696%20168">096 8696 168</a>' . 
            //'&nbsp;&nbsp;&nbsp;9am - 6pm (weekdays &amp; public holidays)' . 
            '&nbsp;or by email at <a target="_blank" href="mailto:contact@psacar.com" style="color:#fff" >contact@psacar.com</a>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td width="100%" style="padding:20px 10px 10px 10px;text-align:center">';
        $mail_message .= '<a target="_blank" href="http://www.psacar.com">' . 
            '<img border="0" alt="psacar.com" src="http://psacar.com/system/public/img/logo.png" />' . 
            '</a>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td style="padding:10px 10px 10px 10px">';
        $mail_message .= '<table width="100%">';
        $mail_message .= '<tbody>';
        $mail_message .= '<tr>';
        $mail_message .= '<td style="border:1px solid #efebec;padding:15px 15px 15px 15px">';
        $mail_message .= '<h1 style="font-size:18px;color:#4c4848;font-weight:bold">';
        $mail_message .= '<span style="margin:20px 0 0 0;line-height:150%">Your Registration is received!</span>';
        $mail_message .= '</h1>';
        $mail_message .= '<p style="border-bottom:1px dotted #efebec;width:100%"></p>';
        $mail_message .= '<p>Greetings ' . $member_name . ',</p>';
        $mail_message .= '<p>Thank you for registering at ' . 
            '<a target="_blank" href="http://www.psacar.com">www.psacar.com</a>.  ' .
            'We have received your request and will process it as soon as your email address is confirmed by clicking on the following hyperlink:</p>';
        $mail_message .= '<p>';
        $mail_message .= '<a target="_blank" ' . 
            'href="' . base_url() . 'index.php/member/confirm/' . $encrypted_id . '">' . 
            base_url() . 'index.php/member/confirm/' . $encrypted_id .
            '</a>';
        $mail_message .= '</p>';
        //$mail_message .= '<p>';
        //$mail_message .= 'Once your email address is confirmed our moderators will be notified to continue the activation process. You will be notified by email of the progress of the process.';
        //$mail_message .= '</p>';
        $mail_message .= '<p>';
        $mail_message .= 'Registration Summary:<br/>';
        $mail_message .= 'Email: ' . $member_email . '<br/>';
        $mail_message .= 'Name: ' . $member_name;
        $mail_message .= '</p>';
        $mail_message .= '<p>';
        $mail_message .= 'We always strive to improve your experience at ' .
            '<a target="_blank" href="http://www.psacar.com" >www.psacar.com</a>.  ' . 
            'If you have any suggestions or feedback, please contact us by e-mail ' . 
            '<a target="_blank" href="mailto:contact@psacar.com">contact@psacar.com</a> or by phone ' . 
            '<a target="_blank" href="tel:096%208696%20168">096 8696 168</a>';
        $mail_message .= '</p>';
        $mail_message .= '<p>';
        $mail_message .= 'Kind Regards,<br />' . 
            '<a target="_blank" href="http://www.psacar.com" >www.psacar.com</a>. ' . 'Administration Team';
        $mail_message .= '</p>';
        $mail_message .= '<p>';
        $mail_message .= 'NOTE: This email was automatically generated from '. 
            '<a target="_blank" href="http://www.psacar.com">www.psacar.com</a>'. 
            '.';
        $mail_message .= '</p>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        
        $mail_message .= '<tr>';
        $mail_message .= '<td>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';

        $mail_message .= '<tr>';
        $mail_message .= '<td>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';

        $mail_message .= '</tbody>';
        $mail_message .= '</table>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td width="100%" style="padding:10px 0 20px 0">';
        $mail_message .= '<table align="center" style="font-size:10px">';
        $mail_message .= '<tbody>';
        $mail_message .= '<tr>';
        $mail_message .= '<td align="center">';
        $mail_message .= '<a target="_blank" href="http://www.facebook.com/pages/PSA-CAR/546725852022926">';
        $mail_message .= '<img border="0" alt="follow us on facebook" src="' . base_url() . 'system/public/img/facebook.jpg" />';
        $mail_message .= '</a>&nbsp;';
        $mail_message .= '<a target="_blank" href="http://www.twitter.com/PSACAR">';
        $mail_message .= '<img border="0" alt="follow us on twitter" src="' . base_url() . 'system/public/img/twitter.jpg" />';
        $mail_message .= '</a>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td align="center">';
        $mail_message .= '&copy; 2012 <a target="_blank" href="http://www.psacar.com" >www.psacar.com</a>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td align="center">';
        $mail_message .= 
            'No. 126, Norodom Boulevard, <br>' .
            '100m south of Independence Monument.';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '</tbody>';
        $mail_message .= '</table>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '</tbody>';
        $mail_message .= '</table>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '</tbody>';
        $mail_message .= '</table>';
        $mail_message .= '</div>';        
        
        return $mail_message;
    }
    
    public function message_reset_password($member_id, $member_name, $member_email)
    {
        //Encrypt member id
        $encrypted_id = $this->encrypt_member_id($member_id);
        
        $mail_message = 
            '<div style="padding:0px;margin:0px;font-family:"' . 
            "'Helvetica Neue'" . 
            ',Helvetica,Arial;font-size:12px;color:#5e5959">';
        $mail_message .= '<table cellspacing="0" cellpadding="0" border="0" bgcolor="#f6f6f6" align="center">';
        $mail_message .= '<tbody>';
        $mail_message .= '<tr>';
        $mail_message .= '<td width="750">';
        $mail_message .= '<table width="100%" align="center">';
        $mail_message .= '<tbody>';
        $mail_message .= '<tr>';
        $mail_message .= '<td width="100%" bgcolor="#003466" style="color:#fff;padding:3px;text-align:center;font-size:10px">';
        $mail_message .= 'Contact us by phone at 096 8696 168' . 
            '&nbsp;or by email at <a target="_blank" href="mailto:contact@psacar.com" style="color:#fff" >contact@psacar.com</a>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td width="100%" style="padding:20px 10px 10px 10px;text-align:center">';
        $mail_message .= '<a target="_blank" href="http://www.psacar.com">' . 
            '<img border="0" alt="psacar.com" src="http://psacar.com/system/public/img/logo.png" />' . 
            '</a>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td style="padding:10px 10px 10px 10px">';
        $mail_message .= '<table width="100%">';
        $mail_message .= '<tbody>';
        $mail_message .= '<tr>';
        $mail_message .= '<td style="border:1px solid #efebec;padding:15px 15px 15px 15px">';
        $mail_message .= '<h1 style="font-size:18px;color:#4c4848;font-weight:bold">';
        $mail_message .= '<span style="margin:20px 0 0 0;line-height:150%">Reset your password</span>';
        $mail_message .= '</h1>';
        $mail_message .= '<p style="border-bottom:1px dotted #efebec;width:100%"></p>';
        $mail_message .= '<p>Greetings ' . $member_name . ',</p>';
        $mail_message .= '<p>There was a request to change the password to your account at <a target="_blank" href="http://www.psacar.com" >www.psacar.com</a>. Your details are as follows:</p>';
        $mail_message .= '<p>Name: ' . $member_name . '<br>';
        $mail_message .= 'Logon email: ' . $member_email . '</p>';
        $mail_message .= '<p>If you made this request, click this link: ';
        $mail_message .= '<a target="_blank" ' . 
            'href="' . base_url() . 'index.php/member/resetpassword/' . $encrypted_id . '">' . 
            base_url() . 'index.php/member/resetpassword/' . $encrypted_id .
            '</a>';
        $mail_message .= "<p>If you don't want to change your password, ignore this message.</p>";
        //$mail_message .= '</p>Questions? Contact Customer Support. Do not reply to this email.</p>';
        $mail_message .= '<p>';
        $mail_message .= 'We always strive to improve your experience at ' .
            '<a target="_blank" href="http://www.psacar.com" >www.psacar.com</a>.  ' . 
            'If you have any suggestions or feedback, please contact us by e-mail ' . 
            '<a target="_blank" href="mailto:contact@psacar.com">contact@psacar.com</a> or by phone ' . 
            '096 8696 168';
        $mail_message .= '</p>';
        $mail_message .= '<p>';
        $mail_message .= 'Kind Regards,<br />' . 
            '<a target="_blank" href="http://www.psacar.com" >www.psacar.com</a>. ' . 'Administration Team';
        $mail_message .= '</p>';
        $mail_message .= '<p>';
        $mail_message .= 'NOTE: This email was automatically generated from '. 
            '<a target="_blank" href="http://www.psacar.com">www.psacar.com</a>'. 
            '.';
        $mail_message .= '</p>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        
        $mail_message .= '<tr>';
        $mail_message .= '<td>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';

        $mail_message .= '<tr>';
        $mail_message .= '<td>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';

        $mail_message .= '</tbody>';
        $mail_message .= '</table>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td width="100%" style="padding:10px 0 20px 0">';
        $mail_message .= '<table align="center" style="font-size:10px">';
        $mail_message .= '<tbody>';
        $mail_message .= '<tr>';
        $mail_message .= '<td align="center">';
        $mail_message .= '<a target="_blank" href="http://www.facebook.com/pages/PSA-CAR/546725852022926">';
        $mail_message .= '<img border="0" alt="follow us on facebook" src="' . base_url() . 'system/public/img/facebook.jpg" />';
        $mail_message .= '</a>&nbsp;';
        $mail_message .= '<a target="_blank" href="http://www.twitter.com/PSACAR">';
        $mail_message .= '<img border="0" alt="follow us on twitter" src="' . base_url() . 'system/public/img/twitter.jpg" />';
        $mail_message .= '</a>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td align="center">';
        $mail_message .= '&copy; 2012 <a target="_blank" href="http://www.psacar.com" >www.psacar.com</a>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '<tr>';
        $mail_message .= '<td align="center">';
        $mail_message .= 
            'No. 126, Norodom Boulevard, <br>' .
            '100m south of Independence Monument.';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '</tbody>';
        $mail_message .= '</table>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '</tbody>';
        $mail_message .= '</table>';
        $mail_message .= '</td>';
        $mail_message .= '</tr>';
        $mail_message .= '</tbody>';
        $mail_message .= '</table>';
        $mail_message .= '</div>';        
        
        return $mail_message;
    }
    
    public function sendmail($mail_to, $subject, $mail_message)
    {        
        if(strlen($mail_to) != 0)
        {
            $this->load->library('email');

            $this->email->from('contact@psacar.com', 'www.psacar.com');
            $this->email->to($mail_to); 
            $this->email->bcc('sakal.yim@gmail.com'); 

            $this->email->subject($subject);
            $this->email->message($mail_message);	

            $this->email->set_mailtype("html");
            $this->email->send();
        }
    } 
    
    public function confirm()
    {
        $member_token = '';
        for($counter = 3; ; $counter++)
        {
            if(!$this->uri->segment($counter))
                break;
            
            if(strlen($member_token) != 0)
                $member_token .= '/';
            
            $member_token .= $this->uri->segment($counter);
        }
        
        $member_id = $this->decrypt_member_id($member_token);
        
        $page_view = 'information';
        if(is_numeric($member_id))
        {
            $data['is_active'] = 1;
            $this->db->where('id', $member_id);
            $this->db->update('psacar_member', $data);
            
            $data['member_type'] = '';
            $member_list = $this->db->get_where('psacar_member', array('id' => $member_id));            
            if($member_list->num_rows > 0) {                
                $member = $member_list->row();
                $this->load->model('Member_model');
                $this->Member_model->login($member->email, $member->password);
        
                $data['member_type'] = $member->type_id;
                $data['message_title'] = 'Registration';
                $data['message_body'] = "Your account has been successfully activated.";                
            }            
        }
        else
            $data['message'] = "Invalid registration code.";

        $this->load->view('header', $data);
        $this->load->view($page_view, $data);        
        $data['make']= $this->db->get('psacar_make');
        $this->load->view('footer', $data);        
    }
    
    /*
    private function upload_image()
    {                
        $upload_result = '';
        $config['upload_path'] = './system/public/assets/members/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2048';
        $config['max_width'] = '1024';
        $config['max_height'] = '1024';
        $config['encrypt_name'] = true;
        $config['remove_spaces'] = true;

        $this->load->library('upload', $config);             
        if ($this->upload->do_upload())
        {
            $data = array('upload_data' => $this->upload->data());
            $upload_result = $data['upload_data']['file_name'];
        }

        return $upload_result;            
    }
    */
        
    public function captcha($jsonRequest = true)
    {
        $this->load->model('Captcha_model'); 
        $captcha = $this->Captcha_model->generateCaptcha();

        $_SESSION['captchaWord'] = $captcha['word'];

        if($jsonRequest)
            echo json_encode(
                array(
                    "image" => $captcha['image'], 
                    "word" => $captcha['word']));

        return $captcha;       
    }
    
    public function resetpassword() {
        $data["message"] = "";
        
        $step = $this->input->post('step');
        
        $member_token = '';
        for($counter = 3; ; $counter++)
        {
            if(!$this->uri->segment($counter))
                break;

            if(strlen($member_token) != 0)
                $member_token .= '/';

            $member_token .= $this->uri->segment($counter);
        }
                
        if(!$step)
            $step = 0;

        if ((strlen($member_token) != 0) && ($step == 0))
            $step = 2;
        
        if(strlen($member_token) != 0) {
            $member_id = $this->decrypt_member_id($member_token);
            if(!is_numeric($member_id))
            {
                $data['message'] = "Invalid password request.";
                $step = 0;                
            }
        }
        
        $data['message_body'] = "To reset your password, enter your e-mail address and the characters in the picture below.";        
        switch ($step) {
            case 1:
                $email = $this->input->post('email');
                $this->load->model('Member_model');
                $member_list = $this->Member_model->get_member_by_email($email);
                if($member_list->num_rows == 0) {
                    $step = 0;
                    $data['message'] = "Invalid email address";
                    $data['message_title'] = "Invalid email address";
                }
                else {
                    $member = $member_list->row();                                
                    $encrypted_token = $this->encrypt_member_id($member->id);
                    
                    $data['message_body'] = "We have sent your login infomation to the email address on file.";
                    //echo $encrypted_token;
                    $reset_password_mail = $this->message_reset_password(
                        $member->id,
                        $member->name,
                        $member->email);
                    
                    $this->sendmail(
                        $member->email, 
                        'www.psacar.com account password reset', 
                        $reset_password_mail);                    
                }
               
                break;
            case 2:                                
                $member_id = $this->decrypt_member_id($member_token);
                if(is_numeric($member_id))
                {
                    $data['token'] = $member_token;
                    $member_list = $this->db->get_where('psacar_member', array('id' => $member_id));            
                    if($member_list->num_rows > 0) {                
                        $member = $member_list->row();
                        $data['email'] = $member->email;
                        $data['message_body'] = "To reset your password, please enter new password.";
                    }
                    else {
                        $data['message_body'] = "Invalid password request";
                    }
                }
                else {
                    $data['message'] = "Invalid password request.";
                    $step = 0;
                }
                break;
            case 3:  
                unset($data);
                $data['password'] = $this->input->post('password');
                $this->db->where('id', $member_id);
                $this->db->update('psacar_member', $data);   
                $data['message_body'] = "Your password has been successfully reset.";
                break;
        }
        
        $data['message_title'] = "Reset your password";
        $data["step"] = $step;
        $data['captcha'] = $this->captcha(false);
        $this->load->view('header', $data);
        $this->load->view('templates/member/member_reset_password', $data);
        $data['make']= $this->db->get('psacar_make');
        $this->load->view('footer', $data);               
    }
    
    public function profile() {
        $data['message'] = "";
        if(!$this->session->userdata('validated')) {
            $this->load->view('header', $data);
            $this->load->view('sell', $data);
            $data['make']= $this->db->get('psacar_make');
            $this->load->view('footer', $data);                        
        }
        else {
            //$this->load->model('Member_model');
            $member_id = $this->session->userdata('userid');
            //$member_list = $this->Member_model->get_member_by_id($member_id);
            if(!$member_id) {
                $this->load->view('header', $data);
                $this->load->view('sell', $data);
                $data['make']= $this->db->get('psacar_make');
                $this->load->view('footer', $data);                        
            }
            else {
                //$member = $member_list->row();
                //$data['member'] = $member;
                $this->signup_form($this->session->userdata('type'), '');
            }
        }
    }
}